package com.senssun.blesample;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.senssun.blesample.adapter.DeviceAdapter;
import com.senssun.blelib.BleManager;
import com.senssun.blelib.callback.BleScanCallback;
import com.senssun.blelib.data.BleDevice;
import com.senssun.blelib.scan.BleScanRuleConfig;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class TestActivity extends Activity {
    String mac = "18:7A:93:6A:7D:EF";
    @BindView(R.id.btn_scan)
    Button btnScan;
    @BindView(R.id.img_loading)
    ImageView imgLoading;
    @BindView(R.id.list_device)
    ListView listDevice;
    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
    Handler handler = new Handler(Looper.getMainLooper());
    @BindView(R.id.tv_content)
    TextView tvContent;
    StringBuffer stringBuffer = new StringBuffer();
    @BindView(R.id.btn_clear)
    Button btnClear;
    @BindView(R.id.btn_dis)
    Button btnDis;
    private DeviceAdapter mDeviceAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        ButterKnife.bind(this);
        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true);
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
//                .setServiceUuids(serviceUuids)      // 只扫描指定的服务的设备，可选
//                .setDeviceName(true, "IF_B7")         // 只扫描指定广播名的设备，可选
//                .setDeviceMac(mac)                  // 只扫描指定mac的设备，可选
//                .setAutoConnect(isAutoConnect)      // 连接时的autoConnect参数，可选，默认false
                .setScanTimeOut(100000 * 1000)              // 扫描超时时间，可选，默认10秒
                .build();

        BleManager.getInstance().initScanRule(scanRuleConfig);
        tvContent.setMovementMethod(ScrollingMovementMethod.getInstance());

        btnScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btnScan.getText().equals(getString(R.string.start_scan))) {
                    mDeviceAdapter.clear();
                    mDeviceAdapter.notifyDataSetChanged();
                    checkPermissions();
                } else if (btnScan.getText().equals(getString(R.string.stop_scan))) {
                    BleManager.getInstance().cancelScan();
                }
            }
        });
        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count=0;
                tvContent.setText("");
                mDeviceAdapter.clear();
                mDeviceAdapter.notifyDataSetChanged();
                BleManager.getInstance().cancelScan();
            }
        });
        btnDis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvContent.setVisibility(View.GONE);
                btnDis.setVisibility(View.GONE);
                listDevice.setVisibility(View.VISIBLE);
            }
        });
        mDeviceAdapter = new DeviceAdapter(this);
        listDevice.setAdapter(mDeviceAdapter);
        mDeviceAdapter.setOnDeviceClickListener(new DeviceAdapter.OnDeviceClickListener() {
            @Override
            public void onConnect(BleDevice bleDevice) {
                mac = bleDevice.getMac();
                tvContent.setVisibility(View.VISIBLE);
                btnDis.setVisibility(View.VISIBLE);
                listDevice.setVisibility(View.GONE);
//                if (!BleManager.getInstance().isConnected(bleDevice)) {
//                    BleManager.getInstance().cancelScan();
//                    connect(bleDevice);
//                }
            }

            @Override
            public void onDisConnect(final BleDevice bleDevice) {


//                if (BleManager.getInstance().isConnected(bleDevice)) {
//                    BleManager.getInstance().disconnect(bleDevice);
//                }
            }

            @Override
            public void onDetail(BleDevice bleDevice) {
//                if (BleManager.getInstance().isConnected(bleDevice)) {
//                    Intent intent = new Intent(MainActivity.this, OperationActivity.class);
//                    intent.putExtra(OperationActivity.KEY_DATA, bleDevice);
//                    startActivity(intent);
//                }
            }
        });
    }

    private void checkPermissions() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            Toast.makeText(this, getString(R.string.please_open_blue), Toast.LENGTH_LONG).show();
            return;
        }

        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }

    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
                    new AlertDialog.Builder(this)
                            .setTitle(R.string.notifyTitle)
                            .setMessage(R.string.gpsNotifyMsg)
                            .setNegativeButton(R.string.cancel,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    })
                            .setPositiveButton(R.string.setting,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                                        }
                                    })

                            .setCancelable(false)
                            .show();
                } else {
                    startScan();
                }
                break;
        }
    }

    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_OPEN_GPS) {
            if (checkGPSIsOpen()) {
//                setScanRule();
                startScan();
            }
        }
    }

    private static final String TAG = "TestActivity";
    Bean bean;
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            stringBuffer.append("体重:" + bean.getWeight() + "    阻抗：" + bean.getZuKang() + "  稳定：" + bean.isIfStable() + "  条数：" + count);
            stringBuffer.append("\n");
            tvContent.setText(stringBuffer.toString());
            int offset = tvContent.getLineCount() * tvContent.getLineHeight();
            if (offset > tvContent.getHeight()) {
                tvContent.scrollTo(0, offset - tvContent.getHeight());
            }
        }
    };
    Bean lastbean;
    int count;

    private void startScan() {
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                btnScan.setText(getString(R.string.stop_scan));
            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
                super.onLeScan(bleDevice);
                if (!mac.equals(bleDevice.getMac())) {
                    return;
                }
                byte[] manuByte = ScannerServiceParser.decodeManufacturer(bleDevice.getScanRecord());
                StringBuffer manuBuffer = new StringBuffer();
                if (manuByte != null) {
                    for (byte byteChar : manuByte) {
                        String ms = String.format("%02X ", byteChar).trim();
                        manuBuffer.append(ms);
                    }
                }
                manuData = manuBuffer.toString();
                Log.e(TAG, getManuData()[1]);
                String data = getManuData()[1];

                if (data.length() >= 14) {
                    byte verify = 0;
                    for (int i = 0; i < data.length() - 2; i += 2) {
                        verify = (byte) (verify + Integer.valueOf(data.substring(i, i + 2), 16));
                    }
                    if (verify == (byte) (Integer.parseInt(data.substring(data.length() - 2, data.length()), 16))) {
                        bean = new Bean(Integer.valueOf(data.substring(0, 2), 16), Integer.valueOf(data.substring(2, 6), 16) * 1f, Integer.valueOf(data.substring(6, 10), 16), data.substring(10, 11).equals("A"), Integer.valueOf(data.substring(11, 12), 16));
                        if (bean.equals(lastbean)) {
                            count++;
                        } else {
                            count = 1;
                            lastbean = bean;
                        }
                        Log.e(TAG, bean.toString());
                        handler.removeCallbacks(runnable);
                        handler.postDelayed(runnable, 50);
                    }
                }
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                mDeviceAdapter.addDevice(bleDevice);
                mDeviceAdapter.notifyDataSetChanged();
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                btnScan.setText(getString(R.string.start_scan));
            }
        });
    }

    String manuData;

    public String[] getManuData() {
        if (manuData != null) {
            String[] ManuData = new String[]{"", ""};
            if (manuData.length() >= 22) {
                ManuData[0] = manuData.substring(0, 22);  //deviceId
                ManuData[1] = manuData.substring(22, manuData.length());//extendData
            }
            return ManuData;
        } else {
            return null;
        }
    }
}
